<template>
    <div>
      <form>
        <input v-model="newItem" placeholder="商品名称"/>
        <input v-model.number="newQuantity" type="number" placeholder="数量" />
        <button type="button" @click="addItem">添加</button>
      </form>
      <h3>购物车:</h3>
      <div v-for="item in cart.items" :key="item.id">
        {{ item.name }}: {{ item.quantity }}
      </div>
    </div>
  </template>
  
  <script>
  import { reactive, ref } from "vue";
  export default {
    setup() {
      const cart = reactive({
        items: [{ id: 1, name: "铅笔", quantity: 1 }],
      });
  
      const newItem = ref("");
      const newQuantity = ref(0);
  
      function addItem() {
        if (newItem.value && newQuantity.value > 0) {
          const newItemData = {
            id: Date.now(),
            name: newItem.value,
            quantity: newQuantity.value,
          };
          cart.items.push(newItemData);
          console.log(`${newItem.value}添加成功`);
          newItem.value = "";
          newQuantity.value = 0;
        }
      }
      return { cart, newItem, newQuantity, addItem };
    }
  }
  </script>
  
  <style scoped>
  input {
    width: 100px;
    height: 30px;
  }
  </style>